/**
 * 渠道管理js文件
 * 
 * @author fb
 */
window.mofang.core.channel = function() {
	var treeNode = null;
	var queryForm = null;
	var params = {data:{page : 1, pagesize : 10}, url : 'core/Channel/pageJson.koala'};
	var cache = {};

	var init = function() {
		groupInit();
		uiInit();
		domEventInit();
		queryForm = $('#chanelQueryForm');
	};
	
	var uiInit = function() {
		_grid.init();
		pageTool.init();
		// select填充
		cache['dbType'] ? util.selectPadData([{domId:'channel_dbType',jsonObj:'dbType'}],cache['dbType']) :
		util.mofangAjax({
			url       : "core/Select/dbType.koala",
			succFun   : function(json) {
				cache['dbType'] = json;
				util.selectPadData([{domId:'channel_dbType',jsonObj:'dbType'}],json);
			}
		});
	};
	
	var groupInit = function() {
		new core.group({renderTo : 'channel_tree', title:'渠道组', url : {
			query  : 'core/Group/getRoots.koala',
			add    : 'core/Group/addChannel.koala',
			del    : 'core/Group/delete.koala',
			update : 'core/Group/update.koala'
		},callback : {
			onClick : function(event, treeId, node) {
				treeNode = node;
				// 只有子点点才加载数据
				params = {data:{page : 1, pagesize : 10}, url : 'core/Channel/pageJson.koala'};
				params.data.group = node.level > 0 ? node.id : null;
				requestData();
			}
		}}).show();
	};
	
	var domEventInit = function() {
		// 查询
		$("#b_channelQuery").unbind('click').bind('click',function(e){
			params.data.page = 1;
			$.extend(params.data, util.serializeJson(queryForm));
			requestData();
		});
		
		$("#b_channelMigration").unbind('click').bind('click',function(e){
			var ids = _grid.getselecValues();
			if (ids.length < 1) {
				$.Prompt('请您选择要操作的数据!');
				return;
			}
			
			migration(ids);
		});
		
		$("#b_channelAdd").unbind('click').bind('click',function(e){
			if (!treeNode || treeNode.children) {
				$.Prompt('请选择渠道组叶子节点后，进行渠道数据添加!');
				return;
			}
			
			addOrupdate();
		});
		
		// 批量删除
		$("#b_channelDel").unbind('click').bind('click',function(e){
			var ids = _grid.getselecValues();
			if (ids.length < 1) {
				$.Prompt('请您选择要操作的数据!');
				return;
			}
			
			deletes(ids);
		});
	};
	
	var view = function(data) {
		new webBox({
			title 			: '详细查看',
			url   			: 'pages/core/channel-view.jsp',
			btn     		: false,
			templateRender	: data
		}).init().show();
	};
	
	var addOrupdate = function(data) {
		var title = data ? '渠道修改' : '渠道添加';
		var url = 'core/Channel/';
			url += data ?  'update.koala' : 'add.koala';
		
		new webBox({
			title 	: title,
			url   	: 'pages/core/channel-addOrupdate.jsp',
			saveFun : function(closeFun) {
				var form = $('#channelForm');
				var datas = util.serializeJson(form);
				if (!Validator.Validate(form[0], 3)) return;
				
				try {
					$.parseJSON(datas.dbTable);
				} catch (e) {
					$.Prompt('表名json格式有误，请您填写正确的数据库表名!');
					return ;
				}
				
				util.mofangAjax({
					url 	: url,
					data 	: datas,
					succFun : function(json) {
						$.Prompt(json.result);
						requestData();
						closeFun();
					}
				});
			}
		}).init().show(function(){
			// 先填充，后面如果是修改才能回显
			cache['dbType'] ? util.selectPadData([{domId:'channel_dbTypeID',jsonObj:'dbType'}],cache['dbType']) :
				util.mofangAjax({
					url       : "core/Select/dbType.koala",
					async     : false,
					succFun   : function(json) {
						cache['dbType'] = json;
						util.selectPadData([{domId:'channel_dbTypeID',jsonObj:'dbType'}],json);
					}
				});
			
			if (data) {
				$('#channelForm').find('input,select,textarea').each(function() {
					this.value = data[this.name];
				});
			} else  {
				var form = $('#channelForm');
				form.find("#channelSn").val(new UUID());
				form.find('#channel_group').val(treeNode.id);
			}
		});
	};
	
	var migration = function(ids) {
		new webBox({
			title 	: "渠道迁移",
			url   	: 'pages/core/channel-migration.jsp',
			height  : 100,
			width   : 500,
			saveFun : function(closeFun) {
				var form = $('#channelSelectForm');
				if (!Validator.Validate(form[0], 3)) return;
				var groupId =  util.serializeJson(form).id;
				if (treeNode.id == groupId) {
					$.Prompt('源与目标渠道相同,不能进行迁移!');
					return;
				}
				
				util.mofangAjax({
					url 	: 'core/Channel/migration.koala',
					data 	: {group : groupId, ids : ids},
					succFun : function(json) {
						requestData();
						$.Prompt(json.result);
						closeFun();
					}
				});
			}
		}).init().show(function(){
			new core.selectGroup({target : 'channelTreeInput', title:'渠道组', checkNode: treeNode, url : {
				query  : 'core/Group/getRoots.koala'
			},onCheck : function(node) {
				$('#channelTreeGroupId').val(node.id);
			}}).show();
		});
	};
	
	var deletes = function(_ids){
		$(this).confirm({
			title   : '系统提示',
			content : '确定要执行渠道删除操作?',
			callBack : function() {
				util.mofangAjax({
					url 	: "core/Channel/delete.koala",
					data 	: {ids : _ids},
					succFun : function(json) {
						$.Prompt(json.result);
						requestData();
					}
				});
			}
		});
	};
	
	var _grid = grid({
		renderTo 	: 'channelGrid', 
	    checkboxs   : {	
	    					checkbox  : true,
	    					checkAll  : true,
	    					dataIndex : 'id'
	    				},
		columns  : [ 	{name : 'id',dataIndex : 'id'}, 
			            {name : '简称',dataIndex : 'name',overflow : true}, 
			            {name : '所属组',dataIndex : 'groupName'}, 
			            {name : '入库类型',dataIndex : 'dbTypeName'}, 
			            {name : '入库表名',dataIndex : 'dbTable',overflow : true}, 
			            {name : '入口',dataIndex : 'entryUrl', overflow : true}, 
			            {name : '代理',dataIndex : 'isUseProxy'}, 
			            {name : '创建时间',dataIndex : 'createDate'}, 
			            {name : '操作',renderer : function(data) {
			            	return '<a id="g_channelView">详细</a>&nbsp;<a id="g_channelUpdate">修改</a>&nbsp;<a id="g_channelDel">删除</a>';
						},
						rendererCall : function(obj) {
							var command = {
									"g_channelView" : function(data){view(data);},
									"g_channelUpdate" : function(data){addOrupdate(data);},
									"g_channelDel" : function(data){deletes([data.id]);}
									};
							
							command[obj.id](obj.data);
						}}]
	});	
	
	var pageTool = page({
		renderTo : "channelPage",
		pageSize : params.data.pagesize,
		subHandler : function(data) {
			params.data.page = data.currNo;
			params.data.pagesize = data.pageSize;
			requestData();
		}
	});
	
	
	var requestData = function() {
		util.mofangAjax({
			url       : params.url,
			data      : params.data,
			succFun   : function(json) {
				_grid.addDatas({
					rowDatas : json.data
				});
				pageTool.render(json.resultCount, params.data.page);
			}

		});
	};
	
	return {
		init : init
	};
};